# _*_ coding:utf-8 _*_
# @Time  : 2023.10.11
# @Author: zizlee
import pathlib
from io import BytesIO
from fastapi import APIRouter, Request
from fastapi.responses import StreamingResponse, FileResponse
from response import APIResponse
from settings import FILE_STORAGE

video_api = APIRouter()


@video_api.get("/files/{filename}")
def read_large_file(filename: str):
    filepath = pathlib.Path(FILE_STORAGE).joinpath(f'video/{filename}')
    if not filepath.exists():
        return APIResponse.no_content(msg='视频文件不存在!')

    # async def get_file_stream(file_path):
    #     with open(file_path, "rb") as file:
    #         chunk = file.read(1024*1024)  # 以 1024KB 的大小读取文件
    #         while chunk:
    #             yield chunk
    #             chunk = file.read(1024*1024)
    # print(filepath.stat().st_size)
    # def get_chunk():
    #     with open(filepath, "rb") as file:
    #         yield file.read(1000)  # 以 1024KB 的大小读取文件

    with open(filepath, "rb") as file:
        chunk = file.read(100)  # 以 1024KB 的大小读取文件
    buf = BytesIO(chunk)
    buf.seek(0)
    # headers = {'Content-Range': 'bytes 0-800000/135419339'}
    return StreamingResponse(buf, media_type="video/mp4")
    # return FileResponse(filepath)


@video_api.post("/files/{filename}")
def read_large_file(filename: str, request: Request):
    filepath = pathlib.Path(FILE_STORAGE).joinpath(f'video/{filename}')
    if not filepath.exists():
        return APIResponse.no_content(msg='视频文件不存在!')
    print(request.headers)
    start = 0
    end = 0
    for k, v in request.headers.items():
        if k == 'range':
            range_data = v.replace('bytes=', '')
            start, end = range_data.split('-')
            start = int(start) if start else 0
            end = int(end) if end else filepath.stat().st_size
    print('range:',  start, end)
    with open(filepath, "rb") as file:
        file.seek(start)
        chunk = file.read(end - start)  # 以 1024KB 的大小读取文件
    buf = BytesIO(chunk)
    buf.seek(0)
    headers = {'Content-Range': 'bytes 0-800000/135419339'}
    return StreamingResponse(buf, media_type="video/mp4", status_code=206, headers=headers)

    # return FileResponse(filepath)
